﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using Xiucai.BPM.Core.Dal;
using Xiucai.BPM.Core.Model;
using Xiucai.Common;
using Xiucai.Common.Data.SqlServer;
using Xiucai.Common.Provider;
using Omu.ValueInjecter;
using Xiucai.Common.Data;
namespace Xiucai.BPM.Core.Bll
{
    public class DevConfigBll
    {
        public static DevConfigBll Instance
        {
            get { return SingletonProvider<DevConfigBll>.Instance; }
        }


        //Get the list for Management!
        //category id is the userid
        public string GetDevListBy(int categoryId)
        {
            var devList = DevConfigDal.Instance.GetListBy(categoryId);
            var list = devList as List<DevConfig> ?? devList.ToList();
            return list.Any() ? JSONhelper.ToJson(list) : "[]";
        }
        public string GetDevListByUid(int uId)
        {
            var devList = DevConfigDal.Instance.GetListBy(uId, "XQH");
            var list = devList as List<DevConfig> ?? devList.ToList();
            return list.Any() ? JSONhelper.ToJson(list) : "[]";
        }
        public string GetDevListByKeyid(int uId)
        {
            var devList = DevConfigDal.Instance.GetListByKeyid(uId);
            var list = devList as List<DevConfig> ?? devList.ToList();
            return list.Any() ? JSONhelper.ToJson(list) : "[]";
        }
        public string GetDevListByPhone(string phone)
        {
            var devList = DevConfigDal.Instance.GetListByPhone(phone).First();
            //var list = devList as List<DevConfig> ?? devList.ToList();
            return devList!=null ? JSONhelper.ToJson(devList) : "[]";
        }

        //Get list via the roles
        public string GetDevListBy(int userID, int roleID)
        {
            var devList = DevConfigDal.Instance.GetListBy(userID, roleID);
            var list = devList as List<DevConfig> ?? devList.ToList();
            return list.Any() ? JSONhelper.ToJson(list) : "[]";
        }
        public string PICDATAShortNames(int role)
        {
            if (role == 0)
            {
                return JSONhelper.ToJson(DevConfigDal.Instance.GetWhere(new { DevType = "PICSB" }).ToList().OrderBy(n => n.DevID)
                                        .Select(n => new
                                        {
                                            id = n.DevContact,
                                            text = "[" + n.DevType + n.DevID + "]",
                                            iconCls = "icon-bullet_green",
                                            attributes = new { username = n.DevOwnerName, devpicid = n.DevContact }
                                        })
                                     );
            }
            else
            {
                return JSONhelper.ToJson(DevConfigDal.Instance.GetWhere(new { DevType = "PICSB", DevOwnerID = role }).ToList().OrderBy(n => n.DevID)
                                        .Select(n => new
                                        {
                                            id = n.DevContact,
                                            text = "[" + n.DevType + n.DevID + "]",
                                            iconCls = "icon-bullet_green",
                                            attributes = new { username = n.DevOwnerName, devpicid = n.DevContact }
                                        })
                                     );
            }
        }
        public string PICShortNames(int role)
        {
            if (role == 0)
            {
                return JSONhelper.ToJson(DevConfigDal.Instance.GetWhere(new { DevType = "PIC" }).ToList().OrderBy(n => n.DevID)
                                        .Select(n => new
                                        {
                                            id = n.DevContact,
                                            text = "[" + n.DevType + n.DevID + "]",
                                            iconCls = "icon-bullet_green",
                                            attributes = new { username = n.DevOwnerName, devpicid = n.DevContact }
                                        })
                                     );
            }
            else
            {
                return JSONhelper.ToJson(DevConfigDal.Instance.GetWhere(new { DevType = "PIC", DevOwnerID = role }).ToList().OrderBy(n => n.DevID)
                                        .Select(n => new
                                        {
                                            id = n.DevContact,
                                            text = "[" + n.DevType + n.DevID + "]",
                                            iconCls = "icon-bullet_green",
                                            attributes = new { username = n.DevOwnerName, devpicid = n.DevContact }
                                        })
                                     );
            }
        }
        //get two names
        public string CBDShortNames(int role)
        {
            if (role == 0)
            {
                return JSONhelper.ToJson(DevConfigDal.Instance.GetWhere(new { DevType = "CBD" }).ToList().OrderBy(n => n.DevID)
                                        .Select(n => new
                                        {
                                            id = n.DevID,
                                            text = "[" + n.DevType + n.DevID + "](" + n.onlinedayscbd + ")",
                                            iconCls = "icon-bullet_green",
                                            attributes = new { username = n.DevOwnerName }
                                        })
                                     );
            }
            else
            {
                return JSONhelper.ToJson(DevConfigDal.Instance.GetWhere(new { DevType = "CBD", DevOwnerID = role }).ToList().OrderBy(n => n.DevID)
                                        .Select(n => new
                                        {
                                            id = n.DevID,
                                            text = "[" + n.DevType + n.DevID + "](" + n.onlinedayscbd + ")",
                                            iconCls = "icon-bullet_green",
                                            attributes = new { username = n.DevOwnerName }
                                        })
                                     );
            }
        }
        public string YBQHarms(int uid)
        {
            object sp = new { userid = uid };
            //SqlParameter sp = new SqlParameter("@userid",uid);
            return JSONhelper.ToJson(DevConfigDal.Instance.GetHarms(sp).ToList().Select(n => new { id = n, text = n, iconCls = "icon-bug" }));
        }
        public string YBQHarmsCount(int ulevel, int alevel, object st, object et, string harms)
        {
            //找下级
            string[] hs = harms.Split(',');
            DataTable dt = new DataTable();
            dt.Columns.Add("area");
            foreach (string c in hs)
            {
                dt.Columns.Add(c);
            }

            var childs = AreaDal.Instance.GetChildren(ulevel);
            foreach (var ch in childs)
            {
                DataRow dr = dt.NewRow();
                dr["area"] = ch.AREA_NAME;
                foreach (string c in hs)
                {
                    object pa = new { ulevel = ch.AREA_ID, area_level = ch.AREA_LEVEL, harm = c, stime = st, etime = et };
                    int count = DbUtils.ExecuteReaderSpValueType<int>("ProHarmCount", pa).First();
                    dr[c] = count;
                }
                dt.Rows.Add(dr);

            }

            return JSONhelper.ToJson(dt);
            //    object sp = new { userid = uid };

            //    return JSONhelper.ToJson(DevConfigDal.Instance.GetHarms(sp).ToList().Select(n => new { id = n, text = n, iconCls = "icon-bug" }));
        }

        //get two names
        public string YBQShortNames(int role)
        {
            if (role == 0)
            {
                return JSONhelper.ToJson(DevConfigDal.Instance.GetWhere(new { DevType = "YBQ" }).ToList().OrderBy(n => n.DevID)
                                        .Select(n => new
                                        {
                                            id = n.DevID,
                                            text = "[" + n.DevOwnerName + "]("+n.onlinedaysybq+")",
                                            iconCls = "icon-bullet_green",
                                            attributes = new { username = n.DevOwnerName, devNote = n.chs, XQHID = n.XQHID }
                                        })
                                     );
            }
            else
            {
                return JSONhelper.ToJson(DevConfigDal.Instance.GetWhere(new { DevType = "YBQ", DevOwnerID = role }).ToList().OrderBy(n => n.DevID)
                                        .Select(n => new
                                        {
                                            id = n.DevID,
                                            text = "[" + n.DevOwnerName + "](" + n.onlinedaysybq + ")",
                                            iconCls = "icon-bullet_green",
                                            attributes = new { username = n.DevOwnerName, devNote = n.chs, XQHID = n.XQHID }
                                        })
                                     );
            }
        }


        //get two names for Xqh
        public string XQHShortNames(int role)
        {
            if (role == 0)
            {
                return JSONhelper.ToJson(DevConfigDal.Instance.GetWhere(new { DevType = "XQH" }).ToList().OrderBy(n => n.DevID)
                                        .Select(n => new
                                        {
                                            id = n.DevID,
                                            text = "[" + n.DevType + n.DevContact + "](" + n.onlinedaysxqh + ")",
                                            iconCls = "icon-bullet_green",
                                            attributes = new { username = n.DevOwnerName, Phone = n.DevContact,XQHlist=n.XQHID }
                                        })
                                     );
            }
            else
            {
                return JSONhelper.ToJson(DevConfigDal.Instance.GetWhere(new { DevType = "XQH", DevOwnerID = role }).ToList().OrderBy(n => n.DevID)
                                        .Select(n => new
                                        {
                                            id = n.DevID,
                                            text = "[" + n.DevType + n.DevContact + "](" + n.onlinedaysxqh + ")",
                                            iconCls = "icon-bullet_green",
                                            attributes = new { username = n.DevOwnerName, Phone = n.DevContact, XQHlist = n.XQHID }
                                        })
                                     );
            }
        }

        private bool HasDevIDCode(int dicCode)
        {
            List<DevConfig> list = DevConfigDal.Instance.GetAll().ToList();
            return list.Any(n => n.DevID == dicCode);
        }

        public int Add(DevConfig d)
        {
            if (HasDevIDCode(d.DevID))
            {
                return 0; //字典编码已存在
            }

            int i = DevConfigDal.Instance.Insert(d);
            if (i > 0)
            {
                LogBll<DevConfig> log = new LogBll<DevConfig>();
                d.DevID = i;
                log.AddLog(d);
            }
            return i;
        }

        public string Edit(DevConfig d)
        {
            int k = -1;
            string msg = "用户编辑失败。";

            DevConfig oldDic = DevConfigDal.Instance.Get(d.KeyId);
            k = DevConfigDal.Instance.Update(d);
            if (k > 0)
            {
                LogBll<DevConfig> log = new LogBll<DevConfig>();
                log.UpdateLog(oldDic, d);
            }

            return new JsonMessage { Data = k.ToString(), Message = msg, Success = k > 0 }.ToString();
        }

        public string Edit(int keyid, string devid)
        {
            int k = -1;
            string msg = "设置失败！";

            //DevConfig oldDic = DevConfigDal.Instance.Get(d.KeyId);
            k = DevConfigDal.Instance.UpdateWhatWhere(new { XQHID = devid }, new { KeyId = keyid });
            if (k > 0)
            {
                msg = "设置成功。";
                //LogBll<DevConfig> log = new LogBll<DevConfig>();
                //log.UpdateLog(oldDic, d);
            }

            return new JsonMessage { Data = k.ToString(), Message = msg, Success = k > 0 }.ToString();
        }
        public string Delete(int keyid, string devtype, int devid)
        {
            string msg = "设备删除失败！";
            DevConfig u = DevConfigDal.Instance.Get(keyid);
            int k = 0;
            if (u != null)
            {
                //删除用户时，同时用户的角色
                using (var conn = new SqlConnection(SqlEasy.connString))
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "delete from t_" + devtype.ToLower() + "status where DevID=@DevID";

                    cmd.InjectFrom<SetParamsValues>(new { DevID = devid });
                    conn.Open();
                    k = cmd.ExecuteNonQuery();
                }
                k = DevConfigDal.Instance.Delete(keyid);
                if (k > 0)
                {
                    msg = "设备删除成功。";
                }
            }
            return new JsonMessage { Data = k.ToString(), Message = msg, Success = k > 0 }.ToString();
        }
    }
}
